<template>
  <div class="shopping-cart" :class="{ empty: !cartItems.length && !loading }">
    <!-- Header -->
    <div class="header">
      <StoreNav
        :title="title"
        :right-text="isManageMode ? '完成' : '管理'"
        @click-left="goBack"
        @click-right="toggleManageMode"
        class="nav-bar--fixed"
      />
    </div>

    <!-- Tabs -->
    <div class="tabs">
      <div
        class="tab"
        :class="{ active: activeTab === 'all' }"
        @click="changeTab('all')"
      >
        全部
        <span class="count" v-if="cartItems.length">{{ cartItems.length }}</span>
      </div>
      <div
        class="tab"
        :class="{ active: activeTab === 'price' }"
        @click="changeTab('price')"
      >
        价格
        <i class="icon-sort" :class="sortOrder"></i>
      </div>
      <div
        class="tab"
        :class="{ active: activeTab === 'filter' }"
        @click="changeTab('filter')"
      >
        筛选 <i class="icon-filter"></i>
      </div>
    </div>

    <!-- Cart Content -->
    <div class="cart-content">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner">
          <div class="spinner-ring"></div>
          <div class="loading-text">加载中...</div>
        </div>
      </div>

      <template v-else>
        <div v-if="!cartItems.length" class="empty-cart">
          <div class="empty-cart-content">
            <div class="empty-cart-icon">
              <svg viewBox="0 0 24 24" width="80" height="80">
                <path fill="#ddd" d="M19 7h-3V6c0-1.7-1.3-3-3-3h-2C9.3 3 8 4.3 8 6v1H5c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zm-9-1c0-.6.4-1 1-1h2c.6 0 1 .4 1 1v1h-4V6z"/>
              </svg>
            </div>
            <div class="empty-cart-text">购物车是空的</div>
            <div class="empty-cart-desc">快去挑选心仪的宠物吧</div>
            <button class="go-shopping-btn" @click="goToPetStore">去逛逛</button>
          </div>
        </div>

        <div v-else class="cart-items">
          <div class="cart-item" v-for="item in sortedCartItems" :key="item.cartId">
            <div class="store-info">
              <div
                class="checkbox"
                :class="{ checked: item.selected }"
                @click="toggleItemSelect(item)"

              >
                <div class="inner-circle"></div>
              </div>
              <div class="store-name" @click="goToDetile(item.productId)">{{ item.name }}<i class="icon-arrow"></i></div>
            </div>

            <div class="product">
              <div class="product-image">
                <img :src="item.imageUrl" :alt="item.name" class="" />
              </div>
              <div class="product-details">
                <div class="product-title">
                  {{ item.name }}
                </div>

                <div class="price-row">
                  <div class="price">
                    <span class="currency">¥</span>
                    <span class="amount">{{ item.price }}</span>
                  </div>
                  <!-- 根据管理模式显示不同的控制按钮 -->
                  <template v-if="!isManageMode">
                    <span>库存: {{ item.stock }}</span>
                    <div class="quantity-control">
                      <button class="minus" @click="decreaseQuantity(item)">-</button>
                      <span class="quantity">{{ item.quantity }}</span>
                      <button class="plus" @click="increaseQuantity(item)">+</button>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- Bottom Bar - 根据管理模式显示不同的底部栏 -->
    <div v-if="cartItems.length > 0" class="checkout-bar">
      <div class="select-all" @click="toggleSelectAll">
        <div class="checkbox" :class="{ checked: isAllSelected }">
          <div class="inner-circle"></div>
        </div>
        <span>全选</span>
      </div>

      <!-- 普通模式底部栏 -->
      <template v-if="!isManageMode">
        <div class="total-info">
          已选{{ selectedCount }}件,合计:
          <span class="total-price">
            <span class="currency">¥</span>
            <span class="amount">{{ calculateTotal }}</span>
            <span class="cents">.00</span>
          </span>
          <div class="discount-info">
            <div>优惠减:¥{{ totalDiscount }}.00</div>
            <div>优惠明细</div>
          </div>
        </div>
        <button class="checkout-button" :disabled="!hasSelectedItems" @click="BuyNow()">领券结算</button>
      </template>

      <!-- 管理模式底部栏 -->
      <template v-else>
        <button class="delete-button" :disabled="!hasSelectedItems" @click="deleteSelected">
          删除所选({{ selectedCount }})
        </button>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import StoreNav from '@/components/storeNav/StoreNav.vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getCartList, deleteCartItem } from '@/views/petStore/api/index'

defineOptions({
  name: 'ShoppingCart',
})

// 声明所有的 ref
const title = ref('购物车')
const cartItems = ref([])
const loading = ref(true)
const totalDiscount = ref(210)
const isManageMode = ref(false)
const activeTab = ref('all')
const sortOrder = ref('desc')

// 计算属性
const isAllSelected = computed(() => {
  return cartItems.value.length > 0 && cartItems.value.every((item) => item.selected)
})

const selectedCount = computed(() => {
  return cartItems.value.filter((item) => item.selected).length
})

const calculateTotal = computed(() => {
  return cartItems.value
    .filter((item) => item.selected)
    .reduce((total, item) => total + item.price * item.quantity, 0)
})

const hasSelectedItems = computed(() => selectedCount.value > 0)

const userStore = useUserStore()
const router = useRouter()

// 添加一个计算属性来控制滚动
const isScrollable = computed(() => {
  return cartItems.value.length > 0 || loading.value
})


// 监听滚动状态变化
watch(isScrollable, (newValue) => {
  if (!newValue) {
    // 当购物车为空时，滚动到顶部
    window.scrollTo(0, 0)
  }
})

// 方法定义
const goToDetile = (productId) => {
  console.log('跳转到商品详情页:', productId)
  router.push({
    name: 'ProductDetail',
    params: { id: productId }
  })
}


const BuyNow = () => {
  // 获取选中的商品
  const selectedItems = cartItems.value.filter(item => item.selected)

  // 计算总价
  const totalPrice = selectedItems.reduce((total, item) => total + item.price * item.quantity, 0)

  // 准备订单信息
  const orderInfo = {
    items: selectedItems,
    totalPrice: totalPrice,
    totalCount: selectedItems.length,
    discount: totalDiscount.value
  }

  // 跳转到订单页面
  router.push({
    path: '/order/cart',
    query: {
      orderInfo: JSON.stringify(orderInfo)
    }
  })
}



const goBack = () => {
  router.go(-1)
}



// 切换单个商品选择状态
const toggleItemSelect = (item) => {
  item.selected = !item.selected
}

// 切换全选状态
const toggleSelectAll = () => {
  const newState = !isAllSelected.value
  cartItems.value.forEach((item) => {
    item.selected = newState
  })
}

// 增加商品数量
const increaseQuantity = (item) => {
  if (item.quantity < item.stock) {
    item.quantity++
  }
}

// 减少商品数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity--
  }
}

// 切换管理模式
const toggleManageMode = () => {
  isManageMode.value = !isManageMode.value
  // 切换模式时清除所有选择
  cartItems.value.forEach((item) => (item.selected = false))
}

// 获取购物车数据
const fetchCartData = async () => {
  try {
    const res = await getCartList()
    if (res.data.code === 200) {
      // 为每个商品添加选择状态和确保数量属性
      cartItems.value = res.data.data.map((item) => ({
        ...item,
        selected: false,
        quantity: item.quantity || 1,
      }))
    } else {
      console.error('获取购物车数据失败:', res.data.message)
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除选中的商品
const deleteSelected = async () => {
  try {
    const selectedIds = cartItems.value
      .filter((item) => item.selected)
      .map((item) => item.productId)
    if (selectedIds.length === 0) return

    const deletePromises = selectedIds.map((id) => deleteCartItem(id))
    console.log('---------------')
    console.log(deletePromises)
    const results = await Promise.allSettled(deletePromises)
    console.log('删除结果:', results)

    // 从本地数据中移除选中的商品
    cartItems.value = cartItems.value.filter((item) => !item.selected)

    // 如果购物车为空，可以自动退出管理模式
    if (cartItems.value.length === 0) {
      isManageMode.value = false
    }
  } catch (error) {
    console.error('删除商品失败:', error)
    // 可以添加错误提示
    // ElMessage.error('删除失败，请重试')
  }
}

// 跳转到宠物商店
const goToPetStore = () => {
  router.push('/petStore')
}

// 添加排序后的购物车列表计算属性
const sortedCartItems = computed(() => {
  let items = [...cartItems.value]

  switch (activeTab.value) {
    case 'all':
      // 默认按添加时间排序
      return items.sort((a, b) => b.cartId - a.cartId)
    case 'price':
      // 按价格排序
      return items.sort((a, b) => {
        return sortOrder.value === 'desc' ? b.price - a.price : a.price - b.price
      })
    case 'filter':
      // 模拟筛选（价格大于1000的商品）
      return items.filter(item => item.price > 1000)
    default:
      return items
  }
})

// 切换标签方法
const changeTab = (tab) => {
  activeTab.value = tab
  if (tab === 'price') {
    sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
  }
}

// 生命周期钩子
onMounted(() => {
  fetchCartData()
})
</script>

<style lang="scss">
// Variables
$primary-color: #8B5CF6; // 主紫色
$price-color: #FF4D4F; // 价格红色
$background-color: #F5F3FF; // 浅紫色背景
$border-color: #E5E7EB;
$text-color: #1F2937;
$secondary-text: #6B7280;
$light-text: #9CA3AF;
$orange: #F59E0B;

// Mixins
@mixin flex($direction: row, $justify: flex-start, $align: center) {
  display: flex;
  flex-direction: $direction;
  justify-content: $justify;
  align-items: $align;
}

@mixin tag {
  font-size: 10px;
  padding: 1px 4px;
  border-radius: 2px;
  margin-right: 4px;
  white-space: nowrap;
}

// Global styles
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  background-color: $background-color;
  color: $text-color;
  font-size: 14px;
  line-height: 1.5;
}

// Shopping cart styles
.shopping-cart {
  max-width: 480px;
  margin: 0 auto;
  background-color: $background-color;
  min-height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden; // 默认禁止滚动

  &.empty {
    height: 100vh;
  }

  &:not(.empty) {
    overflow-y: auto; // 非空状态允许滚动
  }
}

// Cart content styles
.cart-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch; // 增加 iOS 滚动惯性
  padding-bottom: 20px; // 添加额外的底部内边距
}

// Header
.header {
  @include flex(row, space-between);
  padding: 12px 16px;
  background-color: white;
  position: sticky;
  top: 0;
  z-index: 10;

  .back-button {
    width: 24px;
    height: 24px;
    position: relative;

    &::before {
      content: '';
      width: 12px;
      height: 12px;
      border-left: 2px solid $text-color;
      border-bottom: 2px solid $text-color;
      transform: rotate(45deg);
      position: absolute;
      left: 6px;
      top: 6px;
    }
  }

  .title {
    font-size: 16px;
    font-weight: bold;

    span {
      font-weight: normal;
      color: $light-text;
    }
  }

  .right-actions {
    @include flex;
    font-size: 12px;
    color: $light-text;

    .manage {
      margin: 0 8px;
      color: $text-color;
    }

    .more-icon {
      width: 20px;
      height: 20px;
      @include flex(row, space-evenly);

      .dot {
        width: 4px;
        height: 4px;
        background-color: $text-color;
        border-radius: 50%;
      }
    }
  }
}

// Tabs
.tabs {
  @include flex(row, space-around);
  background-color: #f3f0ff;
  padding: 10px 0;
  margin-bottom: 10px;
  margin-top: 14px;
  border-bottom: 1px solid $border-color;

  .tab {
    padding: 0 20px;
    position: relative;
    color: $secondary-text;
    cursor: pointer;
    @include flex(row, center, center);
    gap: 4px;

    .count {
      background-color: $primary-color;
      color: white;
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 10px;
      min-width: 16px;
      text-align: center;
    }

    .icon-sort {
      width: 12px;
      height: 12px;
      position: relative;

      &.desc::before {
        content: '';
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-top: 4px solid currentColor;
      }

      &.asc::before {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-bottom: 4px solid currentColor;
      }
    }

    &.active {
      color: $primary-color;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: -10px;
        left: 50%;
        transform: translateX(-50%);
        width: 20px;
        height: 2px;
        background-color: $primary-color;
      }
    }

    &:hover {
      color: $primary-color;
    }
  }
}

// Cart Items
.cart-items {
  margin: 10px;
  padding-bottom: 50px; // 添加底部内边距，为结算栏留出空间

  .cart-item {
    background-color: white;
    margin-bottom: 10px;
    padding: 12px 16px;
    border-radius: 20px;
    .store-info {
      @include flex;
      margin-bottom: 10px;

      .store-name {
        @include flex;
        font-weight: bold;

        .second-hand-tag {
          @include tag;
          background-color: #4cd964;
          color: white;
          margin-right: 6px;
        }

        .icon-arrow {
          margin-left: 4px;
          width: 12px;
          height: 12px;
          border-right: 1px solid $secondary-text;
          border-bottom: 1px solid $secondary-text;
          transform: rotate(-45deg);
          display: inline-block;
        }
      }
    }

    .store-promotions {
      @include flex;
      margin-bottom: 10px;
      padding-left: 30px;
      font-size: 12px;
      color: $primary-color;

      .promotion {
        @include tag;
        border: 1px solid $primary-color;
        margin-right: 8px;
      }

      .more {
        color: $light-text;
        margin-left: auto;

        .icon-arrow {
          display: inline-block;
          width: 8px;
          height: 8px;
          border-right: 1px solid $light-text;
          border-bottom: 1px solid $light-text;
          transform: rotate(-45deg);
        }
      }
    }

    .product {
      @include flex(row, flex-start, flex-start);
      position: relative;
      .product-image {
        width: 80px;
        height: 80px;
        background-color: #f0f0f0;
        border-radius: 14px;
        margin: 0 10px;
        overflow: hidden;
        border: #ebebeb 1px solid;
        img {
          width: 100%;
          height: 100%;
        }

        .placeholder-image {
          width: 100%;
          height: 100%;
          @include flex(row, center, center);
          font-size: 12px;
          color: $light-text;
        }

        .hidden-image {
          display: none;
        }
      }

      .product-details {
        flex: 1;

        .product-title {
          font-weight: bold;
          margin-bottom: 4px;
          line-height: 1.3;

          .tag {
            @include tag;
            background-color: #f0f0f0;
            color: $secondary-text;
          }

          .apple-icon {
            display: inline-block;
            width: 14px;
            height: 14px;
            background-color: #999;
            border-radius: 50%;
            margin-right: 4px;
            vertical-align: middle;
          }
        }

        .product-subtitle {
          color: $light-text;
          font-size: 12px;
          margin-bottom: 6px;

          .icon-arrow-down {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-right: 1px solid $light-text;
            border-bottom: 1px solid $light-text;
            transform: rotate(45deg);
            margin-left: 4px;
          }
        }

        .product-tags {
          margin-bottom: 4px;

          .tag {
            @include tag;
            border: 1px solid $light-text;
            color: $light-text;

            &.orange {
              color: $orange;
              border-color: $orange;
            }
          }
        }

        .price-tag,
        .gift-tag {
          font-size: 12px;
          color: $orange;
          margin-bottom: 4px;
        }

        .price-row {
          @include flex(row, space-between);
          margin-bottom: 4px;

          position: absolute;
          bottom: 0;
          right: 0;
          gap: 10px;
          .price {
            color: $price-color;

            .currency {
              font-size: 12px;
            }

            .amount {
              font-size: 18px;
              font-weight: bold;
            }

            .original-price {
              font-size: 12px;
              color: $light-text;
              text-decoration: line-through;
              margin-left: 4px;
            }
          }

          .quantity-control {
            @include flex;

            button {
              width: 24px;
              height: 24px;
              border-radius: 50%;
              border: 1px solid $border-color;
              background-color: white;
              @include flex(row, center, center);
              font-size: 16px;
              line-height: 1;
              cursor: pointer;

              &.minus {
                font-size: 18px;
              }
            }

            .quantity {
              margin: 0 10px;
              min-width: 20px;
              text-align: center;
            }
          }
        }

        .paid-info {
          font-size: 12px;
          color: $light-text;
        }
      }
    }
  }
}

// Checkbox
.checkbox {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid $border-color;
  margin-right: 10px;
  position: relative;

  &.checked {
    background-color: $primary-color;
    border-color: $primary-color;

    .inner-circle {
      width: 6px;
      height: 6px;
      background-color: white;
      border-radius: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}

// Checkout Bar
.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  max-width: 480px;
  margin: 0 auto;
  height: 60px;
  background-color: white;
  @include flex(row, space-between);
  padding: 0 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

  .select-all {
    @include flex;
  }

  .total-info {
    flex: 1;
    text-align: right;
    padding-right: 10px;

    .total-price {
      color: $price-color;

      .currency {
        font-size: 12px;
      }

      .amount {
        font-size: 18px;
        font-weight: bold;
      }

      .cents {
        font-size: 12px;
      }
    }

    .discount-info {
      font-size: 10px;
      color: $light-text;
      @include flex(row, flex-end);
      gap: 8px;
    }
  }

  .checkout-button {
    background-color: $price-color;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 8px 20px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background-color: rgba($price-color, 0.9);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }

    &:disabled {
      background-color: rgba($price-color, 0.5);
      cursor: not-allowed;
    }
  }
}

.delete-button {
  background-color: #EF4444; // 更柔和的红色
  color: white;
  border: none;
  padding: 10px 30px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background-color: rgba(#EF4444, 0.9);
    transform: translateY(-1px);
  }

  &:active {
    transform: translateY(0);
  }
}

.delete-button:disabled {
  background-color: #FCA5A5;
  cursor: not-allowed;
}

// Loading Animation
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
  background-color: $background-color;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.spinner-ring {
  width: 40px;
  height: 40px;
  border: 3px solid $border-color;
  border-top-color: $primary-color;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: $secondary-text;
  font-size: 14px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

// Empty Cart Styles
.empty-cart {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 120px); // 减去头部和标签的高度
  background-color: $background-color;
  padding: 20px;
  overflow: hidden; // 确保空购物车状态不滚动

  .empty-cart-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 16px;
  }

  .empty-cart-icon {
    margin-bottom: 8px;
  }

  .empty-cart-text {
    font-size: 18px;
    font-weight: 500;
    color: $text-color;
  }

  .empty-cart-desc {
    font-size: 14px;
    color: $secondary-text;
    margin-bottom: 8px;
  }

  .go-shopping-btn {
    background-color: $primary-color;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 12px 32px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      background-color: rgba($primary-color, 0.9);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }
}
</style>
